package com.yami.shop.api.listener;

import com.google.gson.Gson;
import com.yami.shop.bean.dto.RefundOrderFundTypeDto;
import com.yami.shop.bean.event.PaySuccessOrderEvent;
import com.yami.shop.bean.event.RefundSuccessOrderEvent;
import com.yami.shop.bean.model.OrderRefund;
import com.yami.shop.bean.order.PaySuccessOrderOrder;
import com.yami.shop.bean.order.RefundSuccessOrderOrder;
import com.yami.shop.service.OrderRefundService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component("defaultRefundSuccessOrderListener")
@AllArgsConstructor
@Slf4j
public class RefundSuccessOrderListener {
    @Autowired
    private OrderRefundService orderRefundService;

    @EventListener(RefundSuccessOrderEvent.class)
    @Order(RefundSuccessOrderOrder.DEFAULT)
    public void defaultReceiptOrderListener(RefundSuccessOrderEvent event) {
        String payNo = event.getPayNo();
        String outRefundNo = event.getOutRefundNo();
        BigDecimal amount = event.getAmount();//本次实际退款金额

        OrderRefund one = orderRefundService.lambdaQuery().eq(OrderRefund::getOutRefundNo, outRefundNo).one();
        if(one == null){
            log.error("退款记录不存在");
            return;
        }

        if(one.getReturnMoneySts() == 1){
            log.error("不能重复退款");
            return;
        }

        Gson gson=new Gson();
        RefundOrderFundTypeDto orderFundTypeDto = gson.fromJson(one.getActualityReturnMoneyJson(), RefundOrderFundTypeDto.class);

        orderFundTypeDto.setActualityPayMoney(amount.doubleValue());

        OrderRefund refund=new OrderRefund();
        refund.setRefundId(one.getRefundId());
        refund.setRefundTime(new Date());

        refund.setActualityReturnMoneyJson(gson.toJson(orderFundTypeDto));

        refund.setReturnMoneySts(1);//退款成功
        orderRefundService.updateById(refund);
    }
}
